package com.wangwenjun.concurrency.chapter14.atomicreference;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AtomicReferenceExample1 {

    /**
     * volatile关键字修饰，每次对DebitCard对象引用的写入操作都会被其他线程看到
     * 创建初始DebitCard，账号金额为0元
     */

    private static volatile DebitCard debitCard = new DebitCard("张三", 0);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                DebitCard dc = new DebitCard(debitCard.getAccount(), debitCard.getAmount() + 10);
                //System.out.println(dc);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                debitCard = dc;
                countDownLatch.countDown();
            }, "T-"+i).start();
        }


        countDownLatch.await();

        System.out.println("end:"+debitCard);
    }
}